package dai.samples.shiro.controller;

import dai.samples.shiro.entity.User;
import dai.samples.shiro.service.UserAuthorizationService;
import dai.samples.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "run-as")
public class UserAuthorizationController {

    @Autowired
    private UserAuthorizationService userAuthorizationService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "run-as-other/{targetUserId}")
    public String runAsOther(@PathVariable("targetUserId") Long targetUserId) {
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();
        boolean haveAuthor = userAuthorizationService.existsUserAuthorization(userName, targetUserId);
        if (!haveAuthor) {
            return "授权信息不存在，不能切换";
        }
        User userById = userService.getUserById(targetUserId);
        subject.runAs(new SimplePrincipalCollection(userById.getLoginName(), ""));
        // User switchToUser = userService.findOne(switchToUserId);
        return "身份已切换";
    }

    @RequestMapping(value = "run-auth")
    public String runAuth() {
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();

        return subject.isRunAs() ?
            "当前使用的是授权身份,当前被授权的身份是：" + userName :
            "当前使用的是自己身份：身份是" + userName ;
    }

    @RequestMapping(value = "run-black")
    public String runBlackAuth() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isRunAs()) {
            subject.releaseRunAs();
        }
        return "身份已回退";
    }
}

/*    public String switchTo(
        @CurrentUser User loginUser,
        @PathVariable("switchToUserId") Long switchToUserId,
        RedirectAttributes redirectAttributes) {
        Subject subject = SecurityUtils.getSubject();
        User switchToUser = userService.findOne(switchToUserId);
        if(loginUser.equals(switchToUser)) {
            redirectAttributes.addFlashAttribute("msg", "自己不能切换到自己的身份");
            return "redirect:/runas";
        }
        if(switchToUser == null || !userRunAsService.exists(switchToUserId, loginUser.getId())) {
            redirectAttributes.addFlashAttribute("msg", "对方没有授予您身份，不能切换");
            return "redirect:/runas";
        } 1  2 3 4  5 6  7 8 9
        subject.runAs(new SimplePrincipalCollection(switchToUser.getUsername(), ""));
        redirectAttributes.addFlashAttribute("msg", "操作成功");
        redirectAttributes.addFlashAttribute("needRefresh", "true");
        return "redirect:/runas";
    }*/
